import { onUnmounted, ref } from 'vue'

export function useAccurateTimer() {
    const datetime = ref('');
    const week = ref('');
    let animationFrameId = null;

    function getCurrentDateTime() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const datetimeStr = `${year}-${month}-${day} ${hours}:${minutes}`;

        const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const weekStr = weekdays[now.getDay()];

        return { datetime: datetimeStr, week: weekStr };
    }

    function startAccurateTimer() {
        let lastTime = performance.now();

        function updateTimer() {
            const currentTime = performance.now();
            const elapsedTime = currentTime - lastTime;

            if (elapsedTime >= 1000) { // 每 1000 毫秒（1 秒）更新一次
                lastTime = currentTime;
                const currentDateTime = getCurrentDateTime();
                datetime.value = currentDateTime.datetime;
                week.value = currentDateTime.week;
            }

            animationFrameId = requestAnimationFrame(updateTimer); // 继续循环
        }

        animationFrameId = requestAnimationFrame(updateTimer); // 启动循环
    }

    function stopAccurateTimer() {
        if (animationFrameId) {
            cancelAnimationFrame(animationFrameId);
            animationFrameId = null;
        }
    }

    // 在组件卸载时停止计时器
    onUnmounted(() => {
        stopAccurateTimer();
    });

    return {
        datetime,
        week,
        startAccurateTimer,
        stopAccurateTimer
    };
}